import request from '@/utils/request';

/**
 * 处理 JSON-RPC 响应，提取数据或抛出错误
 * @param {Object} response Axios 响应对象
 * @returns {Object} 成功响应的 result 部分
 * @throws {Error} 如果响应包含错误
 */
function handleResponse(response) {
  if (response?.data?.error) {
    console.error("API Error:", response.data.error);
    throw new Error(response.data.error.message || 'API 请求失败');
  }
  // 直接返回 result 部分，让调用方处理具体内容
  if ('result' in response?.data) {
      return response.data.result;
  }
  // 未知错误或非预期格式
  console.error("Unexpected API response format:", response?.data);
  throw new Error('API 响应格式错误或非预期结果');
}

/**
 * 获取配置值
 * @param {string} path 配置路径
 * @returns {Promise<any>} 配置值
 */
export const getConfig = async (path) => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'get_config_' + Date.now(),
      method: 'config.get',
      params: { path }
    });
    return handleResponse(response);
  } catch (error) {
    console.error(`获取配置失败 [${path}]:`, error);
    throw error instanceof Error ? error : new Error(`获取配置失败: ${path}`);
  }
};

/**
 * 设置配置值
 * @param {string} path 配置路径
 * @param {any} value 配置值
 * @returns {Promise<Object>} 设置结果
 */
export const setConfig = async (path, value) => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'set_config_' + Date.now(),
      method: 'config.set',
      params: { path, value }
    });
    return handleResponse(response);
  } catch (error) {
    console.error(`设置配置失败 [${path}]:`, error);
    throw error instanceof Error ? error : new Error(`设置配置失败: ${path}`);
  }
};

/**
 * 获取YOLOv8模型的类别标签配置
 * @returns {Promise<Array>} 类别标签数组 ["person", "bicycle", ...] (索引即为类别ID)
 */
export const getModelLabels = async () => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'get_model_labels_' + Date.now(),
      method: 'config.get',
      params: {
        name: '/model_manager/yolov8/class_labels'
      }
    });
    return handleResponse(response);
  } catch (error) {
    console.error('获取YOLO类别标签失败:', error);
    throw error instanceof Error ? error : new Error('获取YOLO类别标签失败');
  }
};

/**
 * 更新YOLOv8模型的类别标签配置
 * @param {Array} labels 类别标签数组 ["person", "bicycle", ...] (索引即为类别ID)
 * @returns {Promise<Object>} 更新结果
 */
export const updateModelLabels = async (labels) => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'set_model_labels_' + Date.now(),
      method: 'config.set',
      params: {
        name: '/model_manager/yolov8/class_labels',
        config: labels
      }
    });
    return handleResponse(response);
  } catch (error) {
    console.error('更新YOLO类别标签失败:', error);
    throw error instanceof Error ? error : new Error('更新YOLO类别标签失败');
  }
};

// ==================== 算法管理配置 ====================

/**
 * 获取算法管理配置
 * @returns {Promise<Object>} 算法配置数据
 */
export const getAlgorithmConfig = async () => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'get_algorithm_config_' + Date.now(),
      method: 'config.get',
      params: {
        name: '/algo_manager'
      }
    });
    return handleResponse(response);
  } catch (error) {
    console.error("获取算法配置失败:", error);
    throw error instanceof Error ? error : new Error('获取算法配置失败');
  }
};

/**
 * 更新算法管理配置
 * @param {Object} configData 算法配置数据
 * @returns {Promise<Object>} 更新结果
 */
export const updateAlgorithmConfig = async (configData) => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'set_algorithm_config_' + Date.now(),
      method: 'config.set',
      params: {
        name: '/algo_manager',
        config: configData
      }
    });
    return handleResponse(response);
  } catch (error) {
    console.error("更新算法配置失败:", error);
    throw error instanceof Error ? error : new Error('更新算法配置失败');
  }
};

// ==================== 云端大模型（阿里云百炼）配置 ====================

/**
 * 获取云端大模型配置（/cloud_model）
 */
export const getCloudModelConfig = async () => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'get_cloud_model_' + Date.now(),
      method: 'config.get',
      params: {
        name: '/cloud_model'
      }
    });
    return handleResponse(response) || {};
  } catch (error) {
    console.error('获取云端大模型配置失败:', error);
    throw error instanceof Error ? error : new Error('获取云端大模型配置失败');
  }
};

/**
 * 设置云端大模型配置（/cloud_model）
 */
export const setCloudModelConfig = async (configData) => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'set_cloud_model_' + Date.now(),
      method: 'config.set',
      params: {
        name: '/cloud_model',
        config: configData
      }
    });
    return handleResponse(response);
  } catch (error) {
    console.error('设置云端大模型配置失败:', error);
    throw error instanceof Error ? error : new Error('设置云端大模型配置失败');
  }
};

/**
 * 获取特定算法的配置
 * @param {string} algorithmName 算法名称
 * @returns {Promise<Object>} 算法配置数据
 */
export const getAlgorithmByName = async (algorithmName) => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'get_algorithm_by_name_' + Date.now(),
      method: 'config.get',
      params: {
        name: `/algo_manager/algorithms/${algorithmName}`
      }
    });
    return handleResponse(response);
  } catch (error) {
    console.error(`获取算法${algorithmName}配置失败:`, error);
    throw error instanceof Error ? error : new Error(`获取算法${algorithmName}配置失败`);
  }
};

/**
 * 启用或禁用算法
 * @param {string} algorithmName 算法名称
 * @param {boolean} enabled 是否启用
 * @returns {Promise<Object>} 更新结果
 */
export const toggleAlgorithm = async (algorithmName, enabled) => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'toggle_algorithm_' + Date.now(),
      method: 'config.set',
      params: {
        name: `/algo_manager/algorithms/${algorithmName}/enabled`,
        config: enabled
      }
    });
    return handleResponse(response);
  } catch (error) {
    console.error(`切换算法${algorithmName}状态失败:`, error);
    throw error instanceof Error ? error : new Error(`切换算法${algorithmName}状态失败`);
  }
};

// ==================== 音频输入源配置 ====================

/**
 * 获取音频输入源配置
 * @returns {Promise<Object>} 音频输入源配置 (包含source字段)
 */
export const getAudioInputSource = async () => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'get_audio_input_' + Date.now(),
      method: 'config.get',
      params: {
        name: '/audio_input'
      }
    });
    return handleResponse(response);
  } catch (error) {
    console.error("获取音频输入源配置失败:", error);
    throw error instanceof Error ? error : new Error('获取音频输入源配置失败');
  }
};

/**
 * 设置音频输入源
 * @param {string} source 音频源类型 (builtin/usb)
 * @returns {Promise<Object>} 设置结果
 */
export const setAudioInputSource = async (source) => {
  try {
    const response = await request.post('/v1/jsonrpc2/', {
      jsonrpc: '2.0',
      id: 'set_audio_input_' + Date.now(),
      method: 'config.set',
      params: {
        name: '/audio_input/source',
        config: source
      }
    });
    return handleResponse(response);
  } catch (error) {
    console.error("设置音频输入源失败:", error);
    throw error instanceof Error ? error : new Error('设置音频输入源失败');
  }
};
